from tkinter import Tk, Canvas, Frame, messagebox
from matplotlib import pyplot
from listPage import *
from config import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


class IndexPage(object):

    def __init__(self, master=None):
        # 定义内部变量
        self.root = master
        self.data = self.get_date()
        self.create_matplotlib()
        self.createPage(self.pie)

    def createPage(self, figure):
        self.frame = Frame(self.root, height=800, width=600)
        self.frame.pack()
        toListPage = Button(self.frame, text='返回数据列表', command=self.to_listPage)
        toListPage.pack(anchor=S, side=TOP, padx=10, pady=10)
        canvas = FigureCanvasTkAgg(figure, self.frame)
        canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
        titleLabel = Label(self.frame, text='已有的游戏数据的评分区间占比示例图', font=('微软雅黑', 15))
        titleLabel.pack(anchor=S, side=TOP, padx=10, pady=10)

    # 绘制扇形图
    def create_matplotlib(self):
        # 中文支持
        pyplot.rcParams['font.sans-serif'] = ['SimHei']
        #  用来正常显示中文标签
        # 用来正常显示负号
        pyplot.rcParams['axes.unicode_minus'] = False
        self.pie = pyplot.figure(figsize=(6, 6),facecolor="#F0F0F0")

        # 角度
        explode = []
        # 标签
        labels = []
        if self.data is None:
            self.pie.total_number_chart = pyplot.pie([360], labels=labels, startangle=90, counterclock=False)
        else:
            for d in self.data:
                explode.append(d[1] * 360)
                label = d[0] + '(' + str(d[1] * 100) + '%)'
                labels.append(label)

            self.pie.total_number_chart = pyplot.pie(explode, labels=labels, startangle=90, counterclock=False)

    def get_date(self):
        url = Config.beas_url+'/get_all_game'
        headers = {'user-agent': Config.get_ua(Config)}
        try:
            ret = requests.get(url, headers=headers)
            retJson = json.loads(ret.text)
            list = retJson.get('data')
            return list
        except Exception as e:
            print(e)
            tkinter.messagebox.showerror('错误', '网络异常')
            return None



    def to_listPage(self):
        self.frame.destroy()
        ListPage(self.root)
